package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.auth.utils.RsaUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties props;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String USER_ROLE = "假role";

    /**
     * 用户登录
     * @param username
     * @param password
     * @param response
     */
    public void login(String username, String password, HttpServletResponse response) {
        //跨服务，user-service，查询用户名密码是否匹配

        UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);
        // 生成userInfo, 没写权限功能，暂时都用guest
        UserInfo userInfo = new UserInfo(userDTO.getId(), userDTO.getUsername(),USER_ROLE);

        //加载私钥
        PrivateKey privateKey = null;
        try {
            privateKey = RsaUtils.getPrivateKey("D:/heima/rsa/id_rsa");
            log.info("【授权中心】生成用户token成功");
        } catch (Exception e) {
            log.error("【授权中心】生成用户token失败");
            e.printStackTrace();
        }

        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);

        //将token存入cookie
        CookieUtils.newBuilder()
                .name(props.getUser().getCookieName())
                .value(token)
                .domain(props.getUser().getCookieDomain())
                .maxAge(props.getUser().getCookieMaxAge())
                .httpOnly(true)
                .response(response)
                .build();
    }

    /**
     * 验证用户信息
     * @param request
     * @param response
     * @return
     */
    //页面中有top，top中有shortcut，只要刷新页面，只要页面动，则shortcut中的生命周期函数，会自动执行
    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取cookie
            String token = CookieUtils.getCookieValue(request, props.getUser().getCookieName());
            // 获取token信息
            Payload<UserInfo> payLoad = JwtUtils.getInfoFromToken(token, props.getPublicKey(), UserInfo.class);
            // 获取token的id，校验黑名单
            String id = payLoad.getId();
            Boolean boo = redisTemplate.hasKey(id);
            if (boo != null && boo) {
                // 抛出异常，证明token无效，直接返回401
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            // 获取过期时间
            Date expiration = payLoad.getExpiration();
            // 获取刷新时间
            DateTime refreshTime = new DateTime(expiration.getTime()).plusMinutes(props.getUser().getMinRefreshInterval());
            // 判断是否已经过了刷新时间
            if (refreshTime.isBefore(System.currentTimeMillis())) {
                // 如果过了刷新时间，则生成新token
                token = JwtUtils.generateTokenExpireInMinutes(payLoad.getInfo(), props.getPrivateKey(), props.getUser().getExpire());
                // 写入cookie
                CookieUtils.newBuilder()
                        // response,用于写cookie
                        .response(response)
                        // 保证安全防止XSS攻击，不允许JS操作cookie
                        .httpOnly(true)
                        // 设置domain
                        .domain(props.getUser().getCookieDomain())
                        // 设置cookie名称和值
                        .name(props.getUser().getCookieName()).value(token)
                        // 写cookie
                        .build();
            }
            return payLoad.getInfo();
        } catch (Exception e) {
            log.error("用户信息认证失败",e);
            // 抛出异常，证明token无效，直接返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }


    /**
     * 用户退出
     * @param request
     * @param response
     */
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, props.getUser().getCookieName());
        //解析token
        Payload<Object> payLoad = JwtUtils.getInfoFromToken(token, props.getPublicKey());
        //获取id和有效期剩余时长
        String id = payLoad.getId();
        Long time = payLoad.getExpiration().getTime() - System.currentTimeMillis();
        //写入redis，剩余时间超过5秒以上才写
        if (time > 5000){
            redisTemplate.opsForValue().set(id,"",time, TimeUnit.MICROSECONDS);
        }
        //删除cookie
        deleteCookie(response);
    }

    /**
     * 删除用户Cookie
     * @param response
     */
    private void deleteCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(props.getUser().getCookieName(), "");
        cookie.setDomain(props.getUser().getCookieDomain());
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private ApplicationMapper applicationMapper;

    public String authorize(Long id, String secret) {

        //完成id和密码的校验

        ApplicationInfo applicationInfo = null;
        try {
            applicationInfo = this.applicationMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            log.error("【授权中心】根据id：{},查询服务信息失败", id);
            throw new LyException(ExceptionEnum.DATA_SERVER_BOOM);
        }

        if (null == applicationInfo || !passwordEncoder.matches(secret, applicationInfo.getSecret())) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        AppInfo appInfo = new AppInfo();
        appInfo.setId(id);
        appInfo.setServiceName(applicationInfo.getServiceName());

        appInfo.setTargetList(this.applicationMapper.selectAppTargetList(id));


        try {
            String token = JwtUtils.generateTokenExpireInMinutes(appInfo, props.getPrivateKey(), props.getApp().getExpire());

            log.info("【授权中心】对{}服务生成token成功", applicationInfo.getServiceName());
            return token;
        } catch (Exception e) {
            log.error("【授权中心】对{}服务生成token失败", applicationInfo.getServiceName());
            throw new LyException(ExceptionEnum.SERVER_GENERATE_TOKEN_ERROR);
        }
    }


}
